import requests,execjs,time,re

def get_X_FOR_WITH():   
    # 获取X-FOR-WITH加密字段
    with open('./meituan.js',mode='r',encoding='utf-8') as f:
        ctx = execjs.compile(f.read())
    return ctx.call('get_x')

def get_ct_pois(cityId='59',startDay='20210526',endDay='20210526',keyword=''):
    # 获取酒店id
    # 通过session访问'https://i.meituan.com/ok/204?ndr'，服务器会设置cookie，其中包含有uuid
    # params中的uuid由cookie中的uuid加上时间戳获得
    headers = {
        'Host': 'ihotel.meituan.com',
        'Referer': 'https://hotel.meituan.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
    }
    params = {
        'ndr': ''
    }
    url = 'https://i.meituan.com/ok/204?ndr'
    session = requests.session()
    session.get(url=url,headers=headers,params=params)
    uuid = re.findall('uuid=(.+?)\.',str(session.cookies))

    url = 'https://ihotel.meituan.com/hbsearch/HotelSearch?'
    params = {
        'utm_medium': 'pc',
        'version_name': '999.9',
        'cateId': '20',
        'attr_28': '129',
        'uuid': f'{uuid}@{int(time.time()*1000)}',
        'cityId': cityId,
        'offset': '0',
        'limit': '20',
        'startDay': startDay,
        'endDay': endDay,
        'q': keyword,
        'sort': 'defaults',
        'X-FOR-WITH': get_X_FOR_WITH(),
    }
    rsp = session.get(url=url,headers=headers,params=params)
    ct_pois = rsp.json().get('ct_pois',[])
    return ct_pois

def get_details(poiid):
    # 获取酒店详细数据
    url = 'https://ihotel.meituan.com/group/v2/poi/detail/service?'
    headers = {
        'Host': 'ihotel.meituan.com',
        'Origin': 'https://hotel.meituan.com',
        'Referer': 'https://hotel.meituan.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
    }
    params = {
        'utm_medium': 'pc',
        'version_name': '999.9',
        'poiId': poiid,
        'X-FOR-WITH': get_X_FOR_WITH(),
    }
    rsp = requests.get(url=url,headers=headers,params=params)
    details = rsp.json().get('data',{})
    return details

if __name__ == '__main__':
    cityId = '59'           # 城市id，59为成都
    startDay = '20210526'   # 入住时间
    endDay = '20210526'     # 离店时间
    keyword = ''            # 关键词
    ct_pois = get_ct_pois(cityId,startDay,endDay,keyword)
    for item in ct_pois:
        poiid = item['poiid']
        details = get_details(poiid)
        if details:
            print(details['multiplePoiFeature']['poiName'])
        else:
            print('details获取失败')